import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import { useUserStore } from "./userStore";
import { useWeatherStore } from "./weatherStore";
import { treeManager } from "@/utils/treeManager";
import { useMapStore } from "./mapStore";
import { loadMap } from "@/utils/map";

// 场景类型
export enum SceneType {
  FARM = "farm", // 农场
  HOUSE = "house", // 房屋内部
}

// 场景传送点
export interface Portal {
  id: string;
  sourceScene: SceneType; // 源场景
  targetScene: SceneType; // 目标场景
  sourcePosition: { x: number; y: number }; // 源场景传送点位置
  targetPosition: { x: number; y: number }; // 目标场景传送点位置
  width: number; // 传送点宽度
  height: number; // 传送点高度
}

export const useSceneStore = defineStore("scene", () => {
  const userStore = useUserStore();

  // 当前场景
  const currentScene = ref<SceneType>(SceneType.FARM);

  // 场景是否正在加载中
  const isLoading = ref<boolean>(false);

  // 场景过渡效果
  const transition = reactive({
    active: false, // 是否启用过渡效果
    type: "fade", // 过渡效果类型
    duration: 1000, // 过渡效果持续时间
    progress: 0, // 过渡效果进度
  });

  // 场景传送点列表
  const portals: Portal[] = [
    {
      id: "farm-house",
      sourceScene: SceneType.FARM,
      targetScene: SceneType.HOUSE,
      sourcePosition: { x: 1008, y: 212 },
      targetPosition: { x: 575, y: 534 },
      width: 32,
      height: 8,
    },
    {
      id: "house-farm",
      sourceScene: SceneType.HOUSE,
      targetScene: SceneType.FARM,
      sourcePosition: { x: 579, y: 600 },
      targetPosition: { x: 1008, y: 230 },
      width: 32,
      height: 4,
    },
  ];

  /**
   * 设置当前场景
   */
  const setCurrentScene = (sceneType: SceneType) => {
    currentScene.value = sceneType;
  };

  /**
   * 动画过渡效果
   */
  const animateTransition = () => {
    return new Promise<void>((resolve) => {
      const start = performance.now(); // 开始时间
      const duration = transition.duration;
      function step(now: number) {
        const elapsed = now - start; // 已过去时间
        let p = elapsed / duration; // 进度值
        if (p > 1) p = 1;
        transition.progress = p;
        if (p < 1) {
          requestAnimationFrame(step);
        } else {
          resolve(); // 动画完成
        }
      }
      requestAnimationFrame(step);
    });
  };

  /**
   * 检查玩家是否在传送点上
   */
  const checkPortals = (): Portal | null => {
    const playerPos = userStore.playerPosition;
    const playerSize = userStore.characterSize;

    for (const portal of portals) {
      if (portal.sourceScene !== currentScene.value) {
        continue;
      }

      if (
        playerPos.x < portal.sourcePosition.x + portal.width &&
        playerPos.x + playerSize.width > portal.sourcePosition.x &&
        playerPos.y < portal.sourcePosition.y + portal.height &&
        playerPos.y + playerSize.height > portal.sourcePosition.y
      ) {
        return portal;
      }
    }
    return null;
  };

  /**
   * 切换场景
   * @param targetScene 目标场景
   * @param targetPosition 目标位置
   */
  const changeScene = async (
    targetScene: SceneType,
    targetPosition: { x: number; y: number }
  ) => {
    isLoading.value = true;

    // 开始过渡动画
    transition.active = true;
    transition.progress = 0;

    // 等待过渡动画达到中间点（完全黑屏）
    await new Promise((resolve) => setTimeout(resolve, 250));

    // 更新天气效果
    const weatherStore = useWeatherStore();
    weatherStore.updateWeatherForScene(targetScene);

    // 更新场景和玩家位置 - 在黑屏状态下切换场景
    currentScene.value = targetScene;
    userStore.updatePlayerPosition(targetPosition.x, targetPosition.y);

    // 处理树木可见性和碰撞
    if (targetScene === SceneType.FARM) {
      treeManager.setTreeVisibility(true);
      treeManager.restoreTreeCollisions();
    } else {
      treeManager.setTreeVisibility(false);
      treeManager.disableTreeCollisions();
    }

    // 加载新场景的地图数据

    try {
      console.log("这是场景");
    } catch (error) {
      console.error("加载地图失败:", error);
    }

    // 等待一段时间，确保新场景加载完成
    await new Promise((resolve) => setTimeout(resolve, 250));

    transition.progress = 1;
    transition.active = false;
    isLoading.value = false;
  };

  return {
    portals,
    transition,
    currentScene,
    checkPortals,
    changeScene,
    setCurrentScene,
  };
});
